<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/8/2
 * Time: 17:36
 */

namespace app\api\controller;


use  app\api\model\Order as M;
use think\Db;

class Order extends Base
{
    public function index(){
        $m=new M();
        $post=request()->post();

        $where['isdelete']=0;
        $where['order_status']=[['NEQ',6],['NEQ',7,'or']];//订单查询条件


        $da=[];

        $shu=[];
        $goods=db('goods')->where('goods_id',$post['goods_id'])//获取商品
        ->field('starttime,endtime,tag_id')
            ->find();

        $maiqu= db('order')//获取订单
        ->where('goods_id',$post['goods_id'])
            ->where($where)
            ->where('travel_date',$post['buyDay'])
            ->select();

        if ($post['totalPrice']==0){
            $shu=[
                'code'=>101,
                'msg'=>'免费商品不能单独购买 价格为0 不能下单',
            ];
            echo json_encode($shu); die;
        }


        foreach ($maiqu as $k){
            $shengyu=db('orderperson')->where('order_id',$k['order_id'])->select();
            $ce = db('person')//获取普通商品规格属性
            ->where('specs_id',$post['specs_id'])
                ->where('person_status', 1)
                ->select();
            foreach ($ce as $v){
                foreach ($shengyu as $j){
                    if ($j['person_name'] === $v['person_name']){

                        foreach ($post['personArr'] as $s){

//                                if ($post['person_num_buy']!=0){
//                                   echo  $v['person_num'].'----原数量<br>';
//                                   echo  $j['person_num'].'----已买量<br>';
//                                   echo  $post['person_num_buy'].'----购买量<br>';
                            $person_num = $v['person_num'] - ($j['person_num']+$s['person_num_buy']);
//                                    echo  $person_num.'----差<br>';
                            if ($person_num<0){
                                $tishi=$v['person_name'].'数量库存不足！';
                                $shu=[
                                    'code'=>101,
                                    'msg'=>$tishi,
                                    'data'=>''
                                ];
                                echo json_encode($shu); die;

                            }
//                                }
                        }
                    }
                }

            }

        }

        $mk=model('Marketing')//获取活动
        ->where('goods_id',$post['goods_id'])
            ->where('mk_status',1)
            ->find();

        $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //1.获取字符串的长度
        $length = strlen($str)-1;
        //2.字符串截取开始位置
        $start=rand(0,$length);

        //4.随机截取字符串，取其中的一部分字符串
        $A=substr($str, $start,1);
        $order_no=$A. date('Ymd').rand('5','99999');
        $shu=[];
        // 启动事务

        Db::startTrans();
        try{
            $member=db('member')->where('program_openid',$post['openid'])->find();
//               $dingdan=$m->where('member_id',$member['member_id'])->where('finished_condition',1)->where('isdelete',0)->order('creattime desc')->find();
//               $shujian=  time()-$dingdan['creattime']   ;
//
//                    if ($shujian<1000){
//
//                        $shu=[
//                            'code'=>0,
//                            'msg'=>'有订单还没有完善 前往我的订单查看',
//                            'data'=>'1'
//
//                        ];
//                return json_encode($shu);
//                    }
//                $mem=db('member')->where('member_id',$post['member_id'])->field('member_pcode')->find();
            $order_id=  $m->insertGetId([
                'order_no'=>$order_no,
                'goods_id'=>$post['goods_id'],//商品id
                'member_id'=>$member['member_id'],//会员id
                'original_money'=>$post['totalPrice'],//交易金额
                'fold_money'=>$post['totalPrice'],//交易金额
//                   'cost_ticket_id'=>$coupon_id,//优惠券id
//                   'cost_integral'=>$post['cost_integral'],//购买使用的积分
                'add_integral'=>$post['integral'],//购买获得的积分
                'creattime'=>time(),//下单时间
                'travel_date'=>$post['buyDay'],//出行时间
                'totalnum'=>$post['totalNum'],//购买数量
                'specs_id'=>$post['specs_id'],//规格id
                'finished_condition'=>1,//完成状况
                'member_pcode'=>!empty($member['member_pcode'])?$member['member_pcode']:null//完成状况
            ]);
            foreach ($post['personArr'] as $v){
                db('orderperson')->insert([
                    'person_name'=>$v['person_name'],
                    'person_num'=>$v['person_num_buy'],
                    'person_price'=>$v['person_price'],
                    'order_id'=>$order_id,
                    'chuxing'=>$post['buyDay'],
                    'person_id'=>$v['person_id']
                ]);
            }
            // 提交事务
            Db::commit();
            $shu=[
                'code'=>0,
                'msg'=>'下单成功',
                'data'=>[
                    'order_no'=>$order_no,
                    'order_id'=>$order_id
                ]
            ];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $shu=[
                'code'=>101,
                'msg'=>$e->getMessage(),
                'error'=>$e->getMessage()
//                    ‘'data'=>$data
            ];

        }

        return json_encode($shu);
    }
    public function determine(){//确定订单

        $order_id= input('order_id');
        $shu=[];
        $m=new M();
        Db::startTrans();
        try{
            $order= $m
                ->alias('o')
                ->where('o.order_id',$order_id)
                ->join('goods a','a.goods_id=o.goods_id')
//              ->join('orderperson p','p.order_id=a.order_id')
//              ->join('poi b','a.goods_location=b.id')
                ->field('a.goods_id,a.goods_name as poi_name,a.goods_image,o.travel_date,o.original_money,o.order_id,o.order_no')
                ->find();
            $img=  !empty($order['goods_image'])?explode(',',$order['goods_image']):'';
            if ($img!=''){
                $order['goods_image']=$img[1] ;
            }else{
                $order['goods_image']='';
            }

            $ren=db('orderperson')->where('order_id',$order['order_id'])->field('id,person_name,person_num')->select();
            $order['person']=$ren;

            Db::commit();
            $shu=[
                'code'=>0,
                'msg'=>'查询成功',
                'data'=>$order
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $shu=[
                'code'=>0,
                'msg'=>'查询失败',
                'error'=>$e->getMessage()
//                    ‘'data'=>$data
            ];

        }


        return json_encode($shu);

    }
    public function submit(){
        $post=  request()->post();
        $shu=[];
        $m=new  M();
        $od=$m->where('order_id',$post['order_id'])->find();
        if (!empty($od['updatetime'])){
            $shu=[
                'code'=>305,
                'msg'=>'请不要重复提交订单',
            ];
            return json_encode($shu);
            die();
        }
        Db::startTrans();
        try{
            $coupon= !empty($post['coupon_id'])?$post['coupon_id']:0;
            if ($coupon!=0){
                db('coupondetails')->where('id',$coupon)->update([
                    'usestatus'=>1
                ]);
            }
            $m->where('order_id',$post['order_id'])->Update([
                'finished_condition'=>0,
                'wechat_number'=>$post['wechat_number'],//微信号
                'phone'=>$post['phone'],//手机号
                'fold_money'=>$post['fold_money'],//折扣后的金额
                'updatetime'=>time(),//更新时间
                'cost_ticket_id'=>$coupon,//使用优惠券的id
                'contact_xing'=>$post['contact_xing'],//xing
                'contact_ming'=>$post['contact_ming'],//ming
                'remarks'=>$post['remarks'],//折扣后的金额
                'e_mail'=>$post['e_mail'],//折扣后的金额
            ]);
            Db::commit();
            $shu=[
                'code'=>0,
                'msg'=>'订单ok',
            ];

        } catch (\Exception $e) {
            Db::rollback();

            $shu=[
                'code'=>0,
                'msg'=>'失败',
                'error'=>$e->getMessage()
            ];
        }
        return json_encode($shu);
    }
}